#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <functional>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

namespace Server
{
    using namespace std;
    static const string defaultIp = "0.0.0.0";
    static const int gnum = 1024;
    enum {USAGE_ERR = 1,SOCKET_ERR,BIND_ERR,OPEN_ERR};
    typedef function<void(int,string,uint16_t,string)> func_t;

    class udpServer
    {
    public:
        udpServer(const func_t &cb,const uint16_t &port,const string ip =defaultIp)
        :_callback(cb),_port(port),_ip(ip),_sockfd(-1)
        {
            
        }

        void initServer()
        {
            //创建socket，并且规定协议
            _sockfd = socket(AF_INET,SOCK_DGRAM,0);
            if(_sockfd == -1) 
            {
                cerr << "socket error : " << errno << ":" << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            cout << "socket success " << " : " << _sockfd <<endl;  
            
            //绑定ip,端口
            struct sockaddr_in local; 
            memset(&local,0,sizeof local);
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);    //如果我要给别人发信息，我的port和ip需要发送给对方
            //local.sin_addr.s_addr = inet_addr(_ip.c_str());   //只监听一个ip
            local.sin_addr.s_addr = INADDR_ANY;     //可以监听所有网络
            
            int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
            if(n == -1)
            {
                cerr << "bind error : " << errno << ":" << strerror(errno) << endl;
                exit(BIND_ERR);
            }
            
            //UDP Server 的预备工作已经完成  
        }

        void start()
        {
            //服务器的本质就是一个死循环
            //读取数据
            char buffer[gnum];
            for(;;)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer); 
                ssize_t s = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)&peer,&len);
                
                //1.数据是什么？ 2.谁发的
                if(s>0)
                {
                    buffer[s] = 0;
                    string clientip = inet_ntoa(peer.sin_addr); 
                    uint16_t clientport =ntohs(peer.sin_port);
                    string message = buffer;

                    cout << clientip << "[" << clientport << "]#" << message << endl; 

                    //读取数据做处理
                    _callback(_sockfd,clientip,clientport,message);
                }
            }
        }

        ~udpServer()
        {
        }

    private:
        uint16_t _port; //端口号
        std::string _ip;   //ip地址
        int _sockfd;
        func_t _callback;
    };

}